﻿using System;

namespace ContainerHost.ServiceModel.Dispatcher
{
    /// <summary>
    /// Instance provider implementation.
    /// </summary>
    public class ContainerInstanceProvider : System.ServiceModel.Dispatcher.IInstanceProvider
    {
        #region Properties
        public IContainer Container { get; set; }
        public Type ServiceType { get; set; }
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the ContainerInstanceProvider class.
        /// </summary>
        public ContainerInstanceProvider(Type serviceType)
        {
            ServiceType = serviceType;
            Container = new DefaultContainer();
        }

        /// <summary>
        /// Initializes a new instance of the ContainerInstanceProvider class.
        /// </summary>
        public ContainerInstanceProvider(IContainer container)
        {
            Container = container;
        }
        #endregion

        #region IInstanceProvider Members

        public object GetInstance(System.ServiceModel.InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
        {
            return Container.Resolve(ServiceType);
        }

        public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
        {
            return GetInstance(instanceContext, null);
        }

        public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance)
        {
            //do nothing
        }

        #endregion
    }
}
